package com.nk.iexam.ds;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class TestDBOpenHelper extends SQLiteOpenHelper
{
	private static final String DB_FOLDER = "/data/data/com.nk.iexam/databases/";
	private static final String DB_NAME = "itest.sqlite";
	private static final int DB_VERSION = 1;
	private SQLiteDatabase _database; 
	private final Context _context;
	
	public TestDBOpenHelper(Context context) 
	{
		super(context, DB_NAME, null, DB_VERSION);
		_context = context;	
		_context.deleteDatabase(DB_NAME);
		boolean existed = checkDB();
        if (existed) {
            openDB(); 
        } else {
            createDB();
        }
	}

	/**
	 * Creates a empty database on the system and rewrites it with your own database.
	 */
	public void createDB()
	{
		boolean existed = checkDB();
		if(!existed) {
			this.getReadableDatabase();

			try {
				copyDB();
			} 
			catch (IOException e) {
				e.printStackTrace();
				//throw new Error("Error copying database");
			}
		}
	}
	
	/**
	 * Check if the database already exist to avoid re-copying the file each time you open the application.
	 * @return true if it exists, false if it doesn't
	 */
	private boolean checkDB()
	{
		boolean checkedDb = false;
		String dbPath = DB_FOLDER + DB_NAME;
		File dbfile = new File(dbPath);
		checkedDb = dbfile.exists();

		return checkedDb;
	}

	/**
	 * Copies your database from your local assets-folder to the just created empty database in the
	 * system folder, from where it can be accessed and handled.
	 * This is done by transfering bytestream.
	 * */
	private void copyDB() throws IOException
	{
		//Open your local db as the input stream
		InputStream is = _context.getAssets().open(DB_NAME);

		// Path to the just created empty db
		String dbFilename = DB_FOLDER + DB_NAME;

		//Open the empty db as the output stream
		OutputStream os = new FileOutputStream(dbFilename);

		//transfer bytes from the inputfile to the outputfile
		byte[] buffer = new byte[1024];
		int length;
		while ((length = is.read(buffer))>0){
			os.write(buffer, 0, length);
		}

		//Close the streams
		os.flush();
		os.close();
		is.close();
	}

	public void openDB() throws SQLException
	{
		//Open the database
		String dbPath = DB_FOLDER + DB_NAME;
		_database = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READONLY);
	}

	@Override
	public synchronized void close() {

		if(_database != null) {
			_database.close();
		}

		super.close();

	}
	
	@Override
	public void onCreate(SQLiteDatabase arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
	}
}
